#!/bin/bash

# Detect OS and package manager
if [ -f /etc/redhat-release ]; then
    # CentOS/RHEL
    OS_TYPE="centos"
    PKG_MGR="yum"
    LOG_FILE="/var/log/secure"
    
    # 先尝试不换源安装epel-release
    if ! yum install epel-release -y; then
        echo "[默认源安装失败，切换阿里云源]"
        curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
        curl -o /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
        yum clean all
        yum makecache
        yum install epel-release -y
    fi
    
elif [ -f /etc/debian_version ]; then
    # Debian/Ubuntu
    OS_TYPE="debian"
    PKG_MGR="apt-get"
    LOG_FILE="/var/log/auth.log"
    
    # Update package lists
    apt-get update -y
    apt-get install rsyslog -y
else
    echo "Unsupported OS"
    exit 1
fi

echo "[Installing fail2ban]"
if ! $PKG_MGR install fail2ban -y; then
    if [ "$OS_TYPE" = "centos" ]; then
        echo "[fail2ban安装失败，尝试刷新缓存]"
        yum clean all
        yum makecache
        $PKG_MGR install fail2ban -y || { echo "[安装失败]"; exit 1; }
    else
        echo "[fail2ban安装失败]"
        exit 1
    fi
fi

echo "[Configuring fail2ban for SSH]"
cat > /etc/fail2ban/jail.local <<EOF
[DEFAULT]
ignoreip = 127.0.0.0/8 172.16.0.0/12 10.0.0.0/8 192.168.0.0/16
bantime = 48h
maxretry = 5
findtime = 30
mta = echo

[sshd]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
logpath = $LOG_FILE
maxretry = 5
EOF

echo "[Configuring fail2ban to start on boot]"
if [ "$OS_TYPE" = "centos" ]; then
    systemctl enable fail2ban
    # For CentOS 7, rc.local might not be enabled by default
    if [ ! -f /etc/rc.d/rc.local ]; then
        echo "#!/bin/bash" > /etc/rc.d/rc.local
        chmod +x /etc/rc.d/rc.local
        systemctl enable rc-local
    fi
    grep -q "fail2ban" /etc/rc.d/rc.local || echo "service fail2ban start" >> /etc/rc.d/rc.local
else
    systemctl enable fail2ban
    grep -q "fail2ban" /etc/rc.local || echo "service fail2ban start" >> /etc/rc.local
    chmod +x /etc/rc.local
fi

echo "[Starting fail2ban]"
systemctl start fail2ban

echo "[Checking fail2ban status]"
systemctl status fail2ban --no-pager

echo "Fail2ban installation and configuration complete!"